<template>
    <el-dialog :title="title" :visible.sync="visible" width="560px" append-to-body :close-on-click-modal="false">
        <BaseForm2
            ref="form"
            v-loading="loading"
            label-position="right"
            label-width="86px"
            :fields="fields"
            :text-model="false"
            :data="form"
            size="medium"
            @updateValue="updateEvent"
        >
            <template #des>
                <div>{{ des }}</div>
            </template>
        </BaseForm2>
        <div slot="footer" class="dialog-footer">
            <BaseButton :loading="submitLoading" @click="submitForm">保 存</BaseButton>
            <BaseButton type="recond" @click="cancel">取 消</BaseButton>
        </div>
    </el-dialog>
</template>

<script>
import BaseForm2 from '@/components/BaseForm2'
import { PerformancePredictionModel, AssetRoadSurfaceModel } from '@/models'
import { RoadTypeOptions } from '@/views/technical-evaluation/constants'

export default {
    name: 'AddOrUpdate',
    components: {
        BaseForm2
    },
    data() {
        return {
            model: new PerformancePredictionModel(),
            roadSurfaceModel: new AssetRoadSurfaceModel(),
            title: '新增模型',
            visible: false,
            submitLoading: false,
            loading: false,
            // 表单参数
            form: {},
            id: '',
            fields: [
                {
                    label: '',
                    children: [
                        {
                            key: 'modelName',
                            type: 'input',
                            label: '模型名称',
                            maxlength: '30',
                            'show-word-limit': true,
                            span: 24,
                            placeholder: '请输入',
                            rules: [
                                { required: true, message: '必填项', trigger: ['blur'] },
                                { validator: this.validUnique, trigger: ['blur'] }
                            ]
                        },
                        {
                            options: [],
                            key: 'modelFormula',
                            label: '模型公式',
                            type: 'normal-select',
                            span: 24,
                            placeholder: '请选择',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: RoadTypeOptions,
                            key: 'pavementType',
                            valueKey: 'label',
                            label: '路面类型',
                            type: 'normal-select',
                            span: 24,
                            placeholder: '请选择',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: [],
                            key: 'pavementStructure',
                            valueKey: 'label',
                            label: '路面结构',
                            type: 'normal-select',
                            span: 24,
                            filterable: true,
                            placeholder: '请选择',
                            'popper-class': 'g-line-1 curstom-select',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            type: 'slot',
                            name: 'des',
                            span: 24
                        }
                    ]
                }
            ],
            des: ''
        }
    },
    created() {
        this.getFormualList()
        this.getPavementStructureList()
    },
    methods: {
        validUnique(rule, value, callback) {
            this.model.uniqueCheck({ modelName: value, id: this.id || null }).then((res) => {
                if (!res) {
                    callback(new Error('该名称已存在'))
                } else {
                    callback()
                }
            })
        },
        updateEvent(data) {
            if (data.pavementStructure) {
                this.des = data.pavementStructure
            }
        },
        getFormualList() {
            this.model.getFormualList().then((res) => {
                console.log(res)
                const list = (res.list || []).map((item) => {
                    return {
                        label: item.name,
                        value: item.id
                    }
                })
                list.length > 0 && this.$set(this.fields[0].children[1], 'options', list)
            })
        },
        // 获取路面结构列表
        getPavementStructureList() {
            this.roadSurfaceModel.getPavementStructureList().then((res) => {
                const list = (res || []).map((item) => {
                    return {
                        value: item.id,
                        label: item.name
                    }
                })
                list.length > 0 && this.$set(this.fields[0].children[3], 'options', list)
            })
        },
        // 取消按钮
        cancel() {
            this.visible = false
            this.reset()
        },
        async open(options = {}) {
            const { type, id = null } = options
            this.id = id
            this.visible = true
            this.reset()
            if (type === 'add') {
                this.title = '新增模型'
            } else {
                this.title = '修改模型'
                this.form = await this.getDetail()
            }
        },
        // 表单重置
        reset() {
            this.des = ''
            this.$nextTick(() => {
                this.$refs['form'].resetFields()
            })
        },
        getDetail() {
            this.loading = true
            return this.model.detail({ id: this.id }).finally(() => {
                this.loading = false
            })
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate((valid, res) => {
                if (valid) {
                    console.log(res)
                    this.submitLoading = true
                    this.id && (res.id = this.id)
                    this.model
                        .saveOrUpdate(res)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '操作成功！',
                                duration: 500,
                                onClose: () => {
                                    this.visible = false
                                    this.$emit('success')
                                }
                            })
                        })
                        .finally(() => {
                            this.submitLoading = false
                        })
                } else {
                    this.$message.error('校验失败！')
                }
            })
        }
    }
}
</script>

<style lang="scss">
.curstom-select {
    width: 378px;
}
</style>
